package cn.francis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qfedu.agro.mapper.SysModuleMapper;
import com.qfedu.agro.mapper.SysUserMapper;
import com.qfedu.agro.pojo.SysModule;
import com.qfedu.agro.pojo.SysUser;
import com.qfedu.agro.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Name: UserDetailsServiceImpl
 * Package: cn.francis.service.impl
 * Date: 2024/10/24 - 11:21
 * Description:
 *
 * @author Junhui Zhang
 * @version v1.0
 */

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysModuleMapper sysModuleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, username);
        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        if (sysUser == null) {
            throw new RuntimeException("用户名不存在");
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setSysUser(sysUser);
        List<SysModule> sysModules = sysModuleMapper.selectByUserId(sysUser.getId());
        List<String> cPermissions = sysModules.stream().map(SysModule::getCpermission).toList();
        loginUser.setPermissions(cPermissions);
         return loginUser;
    }
}
